﻿Imports System.Collections
Imports System.Net.Sockets
Imports System.Net

Public Class Handler

    Public workSocket As Socket = Nothing
    Public userID As Integer = -1
    Public Const BufferSize As Integer = 1024
    Public Const HeaderLen As Integer = 13

    Public Sub New(ByVal socket As Socket, Optional ByVal welcome As Boolean = True)
        workSocket = socket

        If welcome Then
            Dim buffer(HeaderLen) As Byte
            buffer(0) = CByte(&H5E)
            buffer(1) = &H8
            buffer(4) = &H0
            buffer(9) = &H0
            workSocket.Send(buffer, HeaderLen, SocketFlags.None)
        End If
    End Sub

    Public Function handle() As Boolean
        Try
            Dim headerBuf(HeaderLen) As Byte
            Dim bytesRead As Integer = 0
            bytesRead = workSocket.Receive(headerBuf, 0, HeaderLen, SocketFlags.Partial)
            If bytesRead = 0 Then
                Return False
            End If
            Dim dataLength As Integer = headerBuf(5)
            Dim buf(dataLength) As Byte
            bytesRead = workSocket.Receive(buf, 0, dataLength, SocketFlags.Partial)
            If bytesRead = dataLength Then
                Dim ph As New PacketHandler(Me)
                ph.handlePacket(buf, 0)
            End If
            Return True
        Catch ex As SocketException
            Return False
        Catch ex As Exception
            log.log(LogType.MSG_DEBUG, "Exception at Handler.handle(): ")
            Console.WriteLine(ex)
            Return False
        End Try
    End Function

End Class
